package com.comtime.usercenter;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.comtime.entity.UserInfo;
import com.comtime.service.MyService;
import com.comtime.smartbox.BaseActivity;
import com.comtime.smartbox.HBApplication;
import com.comtime.smartkilimanjaro.R;
import com.comtime.utils.LogUtils;
import com.comtime.utils.MyConfig;
import com.comtime.utils.MySharedPreferences;
import com.comtime.view.MyDialog;
import com.comyou.comyouhttp.ComyouHttpCallBack;
import com.comyou.comyouhttp.ComyouHttpClient;
import com.comyou.comyouhttp.ComyouHttpProgram;
import com.comyou.customviews.SlideListView;
import com.daimajia.swipe.SwipeLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class AccountManagerActivity extends BaseActivity {

	private String TAG="AccountManagerActivity";
	
	SlideListView listView;
	
	public static String CHILD_ACCOUNT="child_account";
	public static String CHILD_POSITION="child_position";
	public static String ADD_CHILD="com.comtime.smartbox.addchild";
	
	HBApplication application;
	MySharedPreferences mySharedPreferences;
	
	View addView;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_account_manager);
		application=(HBApplication) getApplication();
		mySharedPreferences=MySharedPreferences.getInstance(this);
		init();
		 regist();
		 if(!application.swDevicesList.get(0).checkUserOk){
			 showRemindDialog(getText(R.string.input_user_login_phonenum).toString());
		 }
	}
	
	void regist(){
		IntentFilter filter=new IntentFilter(MyService.ACTION_DISCONNECTED);
		filter.addAction(MyService.ACTION_DELETE_USER_RESULT);
		filter.addAction(MyService.ACTION_CHECK_ALLUSER_RESULT);
		filter.addAction(MyService.ACTION_ADD_USER_RESULT);
		filter.addAction(ADD_CHILD);
		registerReceiver(receiver, filter);
	}
	void init(){
		
		addView=LayoutInflater.from(this).inflate(R.layout.item_add_user, null);
		RelativeLayout relate_add=(RelativeLayout) addView.findViewById(R.id.relate_add);
		relate_add.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent=new Intent(AccountManagerActivity.this,AddChildActivity.class);
				startActivity(intent);
			}
		});
		listView= (SlideListView) findViewById(R.id.listview);
		listView.setRightBtnWidth(dp2px(70));
		listView.addFooterView(addView);
		listView.setAdapter(adapter);
//		listView.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> adapterView, View view, int position,
//					long arg3) {
//				Intent intent=new Intent(AccountManagerActivity.this, DeleteChildActivity.class);
//				intent.putExtra(CHILD_ACCOUNT, accountManagers.get(position).getChild_phonenum());
//				intent.putExtra(CHILD_POSITION,position+1);
//				startActivity(intent);
//				
//			}
//		});
		Log.e("account manager", " sendCheckOutAllUser 33333  ");
		application.swDevicesList.get(0).sendCheckOutAllUser();
	}
	
	public void backAction(View v){
		this.finish();
		overridePendingTransition(R.anim.enter_left, R.anim.exit_right);
	}
	/**
	 * 密码管理
	 * @param 
	 */
	public void PwdManagerAction(View v){
		Intent intent=new Intent(this, ChangeAccountManagerPwdActivity.class);
		startActivity(intent);
	}
	
	String action="";
	BroadcastReceiver receiver=new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context arg0, Intent intent) {
			action=intent.getAction();
			LogUtils.e(TAG, "action: "+action  + AccountManagerActivity.this);
			
			
			if(action.equals(MyService.ACTION_DISCONNECTED)){
				handler.sendEmptyMessage(1);
			}else if(action.equals(MyService.ACTION_CHECK_ALLUSER_RESULT)){
				Log.e("tag", "获取到用户");
				handler.sendEmptyMessage(2);
			}else if(action.equals(MyService.ACTION_DELETE_USER_RESULT)){
				int delete_result_num=intent.getIntExtra(MyService.VALUE_INFO, 0);
				
				Message message=new Message();
				message.what=3;
				message.obj=delete_result_num;
				handler.sendMessage(message);
			}else if(action.equals(ADD_CHILD)){
				String phonenum=intent.getStringExtra(MyService.VALUE_INFO);
				
				
				for (UserInfo item : accountManagers) {
					if(item.getChild_phonenum().equals(phonenum)){
						return;
					}
				}
				UserInfo userInfo=new UserInfo();
				userInfo.setChild_phonenum(phonenum);
				LogUtils.e(TAG, "1111 accountManagers size: "+accountManagers.size());
				accountManagers.add(userInfo);
				LogUtils.e(TAG, "2222 accountManagers size: "+accountManagers.size());
				getinfo();
				listView.deleteItem();
				adapter.notifyDataSetChanged();
			} else if (action.equals(MyService.ACTION_ADD_USER_RESULT)) {
				
				LogUtils.e(TAG, "ACTION_ADD_USER_RESULT " );
				
				int add_result_num = intent
						.getIntExtra(MyService.VALUE_INFO, 0);
				Message message = new Message();
				message.what = 5;
				message.obj = add_result_num;
				handler.sendMessage(message);

            }

        }
    };

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    showToast(getText(R.string.device_dis_connect).toString());
                    AccountManagerActivity.this.finish();
                    overridePendingTransition(R.anim.enter_left, R.anim.exit_right);
                    break;
                case 2:
                    //查询用户结果
                    if (accountManagers != null) {
                        accountManagers.clear();
                        adapter.notifyDataSetChanged();
                    }

                    LogUtils.e(TAG, "3333 accountManagers size: " + accountManagers.size());
                    List<UserInfo> infos = application.swDevicesList.get(0).userInfos;
                    accountManagers.addAll(infos);
                    LogUtils.e(TAG, "4444 accountManagers size: " + accountManagers.size());


					getinfo();
                    listView.deleteItem();
                    adapter.notifyDataSetChanged();
                    Log.e("tag", "获取到用户：" + accountManagers.size());
                    break;
                case 3:
                    //删除用户结果
                    int delete_result_num = (Integer) msg.obj;
                    if (delete_result_num == 0) {
                        showToast(getText(R.string.delete_child_fail).toString());
                        listView.deleteItem();
                        adapter.notifyDataSetChanged();
                    } else {
                        showToast(getText(R.string.delete_child_success).toString());
                        accountManagers.remove(delete_item);
                        listView.deleteItem();
                        adapter.notifyDataSetChanged();
                    }

                    break;
                case 4:
                    adapter.notifyDataSetChanged();
                    break;
                case 5:
                    // 添加用户结果
                    int add_result_num = (Integer) msg.obj;
                    if (add_result_num == 0) {
                        showToast(getString(R.string.add_child_fail).toString());
                    } else {
                        showToast(getString(R.string.add_child_success).toString());
                        Intent intent = new Intent(AccountManagerActivity.ADD_CHILD);
                        intent.putExtra(MyService.VALUE_INFO, mySharedPreferences.getPhoneNum());
                        sendBroadcast(intent);

                    }

                    break;
                default:
                    break;
            }
        }

        ;
    };

   /* private Map<String, List<String>> dataset = new HashMap<String, List<String>>();
    private ArrayList<String> parentList;
    private ArrayList<String> childList;

    public void initDatas() {

        String mac;
        parentList = new ArrayList<String>();

        parentList.add("343");
        parentList.add("979");
        initDataSet();


    }

    public void initDataSet() {
        dataset.clear();
        for (String info : parentList) {
            childList = new ArrayList<String>();
            childList.add("17771861240");
            childList.add("17771861241");
            dataset.put(info, childList);
        }
    }


    //expandableListview

    private SwipeLayout currentExpandedSwipeLayout;
    BaseExpandableListAdapter expandAdapter = new BaseExpandableListAdapter() {
        @Override
        public int getGroupCount() {
            return dataset.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            if (dataset.get(parentList.get(groupPosition)) == null) {
                return 0;
            }
            return dataset.get(parentList.get(groupPosition)).size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return parentList.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return dataset.get(parentList.get(groupPosition)).get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }


        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

            if (convertView == null) {

                convertView = LayoutInflater.from(AccountManagerActivity.this).inflate(R.layout.group_layout, null);
            }
            convertView.setTag(R.layout.group_layout, groupPosition);
            convertView.setTag(R.layout.expandlist_item, -1);
            TextView text = (TextView) convertView.findViewById(R.id.group_title);
            text.setText(parentList.get(groupPosition));
            ImageView img = (ImageView) convertView.findViewById(R.id.group_img);
            if (isExpanded) {
                img.setBackgroundResource(R.drawable.icon_detail_down_button);
            } else {
                img.setBackgroundResource(R.drawable.icon_detail_pull_button);
            }
            return convertView;
        }


        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

            if (convertView == null) {

                convertView = LayoutInflater.from(AccountManagerActivity.this).inflate(R.layout.expandlist_item, null);

            }
            convertView.setTag(R.layout.group_layout, groupPosition);
            convertView.setTag(R.layout.expandlist_item, childPosition);
            TextView tv_num = (TextView) convertView.findViewById(R.id.tv_num);
            TextView tv_name = (TextView) convertView.findViewById(R.id.tv_name);
            Button btn_delete = (Button) convertView.findViewById(R.id.ib_delete);
            final SwipeLayout child = (SwipeLayout) convertView.findViewById(R.id.child);
            tv_num.setText(getText(R.string.normal_user).toString() + (childPosition + 1));
            final String phone = dataset.get(parentList.get(groupPosition)).get(childPosition);
            tv_name.setText(phone);
            //btn_delete.setTag(childPosition);
            //滑动卡顿
            child.setShowMode(SwipeLayout.ShowMode.PullOut);
            child.addDrag(SwipeLayout.DragEdge.Right, child.findViewWithTag("button"));
            child.addSwipeListener(new SwipeLayout.SwipeListener() {
                @Override
                public void onStartOpen(SwipeLayout layout) {
                    if (currentExpandedSwipeLayout != null && currentExpandedSwipeLayout != layout)
                        currentExpandedSwipeLayout.close(true);

                }

                @Override
                public void onOpen(SwipeLayout layout) {
                    currentExpandedSwipeLayout = layout;


                }

                @Override
                public void onStartClose(SwipeLayout layout) {

                }

                @Override
                public void onClose(SwipeLayout layout) {
                }

                @Override
                public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {

                }

                @Override
                public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {

                }
            });

            btn_delete.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (v.getId()) {
                        case R.id.ib_delete:
                            //TODO:删除授权用户
                            String mac = parentList.get(groupPosition);
                            //上传mac 和手机号删除用户
                            ComyouHttpProgram httpProgram = new ComyouHttpProgram();
                            httpProgram.add("phoneNum", phone);
                            httpProgram.add("mac", mac);
                            ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
                                    + "deletesubaccount.php");
                            httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

                                @Override
                                public void onFailure(String s, IOException e) {

                                }

                                @Override
                                public void onResponse(String string) {
                                    //从列表中删除


                                }
                            });

                            *//**//*List<String> lists = dataset.get(parentList.get(groupPosition));
                            //dataset.get(parentList.get(groupPosition)).remove(childPosition);
                            lists.remove(childPosition);
                            Log.e("RZCDA","LI SIZE" + lists.size()+"-----panrent = "+parentList.get(groupPosition)+" ----- dataset ="+dataset.size());
                            dataset.put(parentList.get(groupPosition),lists);
                            Log.e("RZCDATA","1L SIZE = "+dataset.get(parentList.get(0)).size()+"----2L SIZE = "+dataset.get(parentList.get(1)).size());*//**//*
                            dataset.get(parentList.get(groupPosition)).remove(childPosition);
                            expandAdapter.notifyDataSetChanged();
                            *//**//*Intent intent = new Intent(AccountManagerActivity.this, Activity_3.class);
                            startActivity(intent);*//**//*
                            break;

                        default:
                            break;
                    }
                }
            });
            return convertView;
        }*//*

        OnClickListener clickListener = new OnClickListener() {
            //TODO:点击删除，删除对应授权用户
            @Override
            public void onClick(View view) {
                delete_item = (Integer) view.getTag();
                Log.e(TAG, "  delete_item: " + delete_item);
                switch (view.getId()) {
                    case R.id.ib_delete:

                        application.swDevicesList.get(0).sendDeleteUserPhone(accountManagers.get(delete_item).getChild_phonenum());
                        break;

                    default:
                        break;
                }
            }
        };

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    };*/


    BaseAdapter adapter = new BaseAdapter() {

        @Override
        public int getItemViewType(int position) {
            return 1;
        }


        @Override
        public View getView(int position, View view, ViewGroup group) {

            ViewHolder holder = null;
            if (view == null) {
                holder = new ViewHolder();
                //view=LayoutInflater.from(AccountManagerActivity.this).inflate(R.layout.list_item_account, null);
                view = LayoutInflater.from(AccountManagerActivity.this).inflate(R.layout.list_item_account, null);
                holder.tv_num = (TextView) view.findViewById(R.id.tv_num);
                holder.tv_name = (TextView) view.findViewById(R.id.tv_name);
                holder.btn_delete = (Button) view.findViewById(R.id.ib_delete);

                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            int num = position + 1;
            holder.tv_num.setText(getText(R.string.normal_user).toString() + num);
            holder.tv_name.setText(accountManagers.get(position).getChild_phonenum());
            holder.btn_delete.setTag(position);
            holder.btn_delete.setOnClickListener(clickListener);

            return view;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return accountManagers == null ? 0 : accountManagers.size();
        }

        OnClickListener clickListener = new OnClickListener() {

            @Override
            public void onClick(View view) {
                delete_item = (Integer) view.getTag();
                Log.e(TAG, "  delete_item: " + delete_item);
                switch (view.getId()) {
                    case R.id.ib_delete:

                        application.swDevicesList.get(0).sendDeleteUserPhone(accountManagers.get(delete_item).getChild_phonenum());
                        //TODO:删除用户，最好是在固件中查找删除，然后也在服务器上删除

                        break;

                    default:
                        break;
                }
            }
        };
    };

	int delete_item=-1;
    private class ViewHolder {
        TextView tv_num;
        TextView tv_name;
        Button btn_delete;
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        //initDatas();
		getinfo();
        adapter.notifyDataSetChanged();
    }



    /**
     * 获取账户信息
     */
    List<UserInfo> accountManagers = new ArrayList<UserInfo>();

    void getinfo() {
        if (accountManagers != null && accountManagers.size() >= 4) {
			addView.setVisibility(View.INVISIBLE);
        } else {
			addView.setVisibility(View.VISIBLE);
        }
    }


    MyDialog myDialog;

    /**
     * 提示用户点击
     *
     * @param str
     */
    private void showRemindDialog(String str) {

        if (myDialog != null) {
            myDialog.cancel();
        }
        myDialog = new MyDialog(AccountManagerActivity.this);
        myDialog.setTitle(str);
        myDialog.setContent(mySharedPreferences.getPhoneNum());
        myDialog.setLeftButtonText(getText(R.string.ok));
        myDialog.setCancelable(false);
        myDialog.getLeftButton().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                myDialog.dismiss();
                application.swDevicesList.get(0).sendAddUserPhone(mySharedPreferences.getPhoneNum());
            }
        });
        myDialog.show();
    }


    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    /**
     * 自定义提示语
     *
     * @param str
     */
    Toast toast = null;

    void showToast(String str) {
        if (toast != null) {
            toast.cancel();
        }
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.toastshow, null);
        TextView textView = (TextView) view.findViewById(R.id.toastshow);
        textView.setText(str);
        Toast toast = new Toast(this);
        double d = getResources().getDisplayMetrics().density;
        toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(view);
        toast.show();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}
